package org.jeecg.modules.thirdpartyapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.ThirdPartyApi;
import org.jeecg.common.util.ApiSignUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.qyxx.enumdemo.RedisKeyConstant;
import org.jeecg.modules.syncdata.entity.SyncLog;
import org.jeecg.modules.syncdata.entity.SyncResult;
import org.jeecg.modules.thirdpartyapi.constant.BgApiEnum;
import org.jeecg.modules.thirdpartyapi.dto.AuthUserInfoDto;
import org.jeecg.modules.thirdpartyapi.dto.PullDto;
import org.jeecg.modules.thirdpartyapi.dto.SyncLogDto;
import org.jeecg.modules.thirdpartyapi.service.BgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * bg控制器
 *
 * @author zhanglei01
 * @date 2022/03/04
 */
@Api(value = "外部接口", tags = "外部接口")
@Slf4j
@ThirdPartyApi(responseZip = true)
@RestController
@RequestMapping("/bg/api")
public class BgController {

    @Autowired
    private BgService bgService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 三方 api
     * 实体类添加 @ThirdPartyEntity(ignore = true) 可忽略返回
     *
     * @param apiName api名称
     * @param dto     dto
     * @return {@link Result}
     */
    @ApiOperation(value = "外部api")
    @PostMapping("/{apiName}")
    public Result bgApi(@PathVariable String apiName, @Validated @RequestBody PullDto dto) {
        BgApiEnum bgApiEnum = null;
        try {
            bgApiEnum = BgApiEnum.valueOf(apiName);
        } catch (IllegalArgumentException e) {
            return Result.error("接口不存在");
        }
        TableInfo tableInfo = TableInfoHelper.getTableInfo(bgApiEnum.getValue());
        IPage<Map<String, Object>> mapIPage = bgService.pullDataByUpdate(tableInfo, dto);
        return Result.OK(mapIPage);
    }

    @ApiOperation(value = "缓存用户信息")
    @PostMapping("/cacheUserInfo")
    public Result<?> cacheUserInfo(@Validated @RequestBody AuthUserInfoDto userInfo) {
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        String fullKey = RedisKeyConstant.AUTH_USER_KEY + key;
        JSONObject data = new JSONObject();
        if (redisUtil.setString(fullKey, JSON.toJSONString(userInfo), RedisKeyConstant.AUTH_USER_KEY_EXPIRE)) {
            data.put("key", key);
            return Result.OK(data);
        } else {
            return Result.error("缓存用户信息失败");
        }

    }

    @ApiOperation(value = "获取报告同步记录")
    @ThirdPartyApi(responseZip = false)
    @PostMapping("/getSyncLog")
    public Result getSyncLog(@Validated @RequestBody SyncLogDto syncLogDto) {
        if ("sync_log".equals(syncLogDto.getLogType()) && StringUtils.isNotBlank(syncLogDto.getDataMsg())) {
            String msg = ApiSignUtil.unGzip(syncLogDto.getDataMsg());
            List<SyncLog> syncLogs = JSON.parseArray(msg, SyncLog.class);
            bgService.saveSyncLog(syncLogs);
        }
        if ("sync_result".equals(syncLogDto.getLogType()) && StringUtils.isNotBlank(syncLogDto.getDataMsg())) {
            String msg = ApiSignUtil.unGzip(syncLogDto.getDataMsg());
            List<SyncResult> syncResults = JSON.parseArray(msg, SyncResult.class);
            bgService.saveSyncResult(syncResults);
        }
        return Result.OK();
    }
}
